<?php
declare (strict_types = 1);

namespace app\controller;

use app\common\BaseController;
use app\service\CategoryService;
use app\service\GoodsService;
use app\service\HouseOutService;
use app\service\InnerPurchaseService;
use app\service\UserService;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use think\Request;

class HouseOutController extends BaseController
{
  /**
   * 获取仓库出库信息列表
   */
  public function index(Request $request){
    $page = $request->param('page', 1);
    $pageSize = $request->param('pageSize', env('pager.default.size'));
    $data['process'] = $request->param('process', '');

    if ($data['process'] === '') {
      return $this->send400Response('process必填');
    }
    $conditions = [
      ['h.status', 1,'=']
    ];
    if(strlen($data['process']) > 0){
      $conditions[] = ['h.process',$data['process'],'='];
    }
    $list = HouseOutService::getInstance()->getHouseOutJoinGoods($conditions);
    // 获取分类
    $category = CategoryService::getInstance()->getCategoryByCondition([['base', 0, '=']]);
    $category = array_column($category, 'category_name', 'id');
    // 获取门店
    $store = UserService::getInstance()->storeAll();
    $store = array_column($store, 'basename', 'base');
    foreach ($list as &$value) {
      $value['category'] = isset($category[$value['category_id']]) ? $category[$value['category_id']] : '';
      $value['base_name'] = isset($store[$value['base']]) ? $store[$value['base']] : '';
    }
    // 分页
    $count = count($list); //总条数
    $start=intval(($page - 1) * $pageSize); //偏移量，当前页-1乘以每页显示条数
    $pager = [
      'totalCount' => $count,
      'pageSize' => intval($pageSize),
      'currPage' => intval($page),
      'totalPage' => intval($count/$pageSize)+1
    ];

    $data = array_slice($list, $start, intval($pageSize));
    return $this->send200ResponseWithPager($data,$pager);
  }

  /**
   * 获取仓库出库订单列表
   */
  public function order(Request $request) {
    $page = $request->param('page', 1);
    $pageSize = $request->param('pageSize', env('pager.default.size'));
    $base = $request->param('base', '');
    $houseSell = $request->param('houseSell', '');
    $process = $request->param('process', '');
    $conditions = [];
    if($base){
      $conditions[] = ['o.base', $base, '='];
    }
    if ($houseSell !== '') {
      $conditions[] = ['o.house_sell', $houseSell, '='];
    }
    if ($process !== '') {
      $conditions[] = ['ho.process', $process, '='];
    }
    $list = InnerPurchaseService::getInstance()->getInnerJoinHouseOut($conditions);
    // 分页
    $count = count($list); //总条数
    $start=intval(($page - 1) * $pageSize); //偏移量，当前页-1乘以每页显示条数
    $pager = [
      'totalCount' => $count,
      'pageSize' => intval($pageSize),
      'currPage' => intval($page),
      'totalPage' => intval($count/$pageSize)+1
    ];
    $data = array_slice($list, $start, intval($pageSize));
    return $this->send200ResponseWithPager($data,$pager);

  }

  /**
   * 导出至excel
   */
  public function export(Request $request) {
    $process = $request->param('process', '');
    $groupid = $request->param('groupid', '');
    $endTime = $request->param('endTime', '');
    $startTime = $request->param('startTime', '');
    $base = $request->param('base', '');
    if ($process === '') {
      return $this->send400Response('process必填');
    }
    if ($groupid === '') {
      return $this->send400Response('groupid必填');
    }
    $startTime = $startTime ? date('Y-m-d', strtotime($startTime)) : '';
    $endTime = $endTime ? date('Y-m-d', strtotime($endTime) + (24 * 60 * 60)) : '';
    $conditions = [
      ['h.status', 1,'='],
      ['h.process',$process,'=']
    ];
    if ($startTime) {
      $conditions[] = ['h.sale_time', $startTime, '>='];
    }
    if ($endTime) {
      $conditions[] = ['h.sale_time', $endTime, '<'];
    }
    if ($base !== '') {
      $conditions[] = ['h.base', $base, '='];
    }
    $list = HouseOutService::getInstance()->getHouseOutJoinGoods($conditions);
    // 获取门店
    $store = UserService::getInstance()->storeAll();
    $store = array_column($store, 'basename', 'base');
    // 合计
    $total = [
      'insert_time' => '合计',
      'sell_number' => '',
      'category_name' => '',
      'name' => '',
      'sale_time' => '',
      'unit' => '',
      'count' => 0,
      'price' => '',
      'total_cost' => 0,
      'type' => '',
      'sell_price' => '',
      'total_sell' => 0,
      'base_name' => '',
      'comment' => '',
    ];
    foreach ($list as &$value) {
      $value['base_name'] = isset($store[$value['base']]) ? $store[$value['base']] : '';
      $value['insert_time'] = date('Y-m-d', strtotime($value['insert_time']));
      $value['sale_time'] = date('Y-m-d', strtotime($value['sale_time']));
      $value['total_cost'] = round($value['price'] * $value['count'], 2);
      $value['type'] = $value['type'] === 1 ?  '加工' : '售出';
      $value['total_sell'] = round($value['sell_price'] * $value['count'], 2);
      $total['count'] += $value['count'];
      $total['total_cost'] += $value['total_cost'];
      $total['total_sell'] += $value['total_sell'];
    }
    $list[] = $total;

    $spreadsheet = new Spreadsheet();
    $sheet = $spreadsheet->getActiveSheet();
    if ($groupid === 0 || $groupid === 2) {
      $sheet->getColumnDimension('A')->setWidth(20);
      $sheet->getColumnDimension('B')->setWidth(15);
      $sheet->getColumnDimension('C')->setWidth(15);
      $sheet->getColumnDimension('D')->setWidth(20);
      $sheet->getColumnDimension('E')->setWidth(15);
      $sheet->getColumnDimension('F')->setWidth(15);
      $sheet->getColumnDimension('G')->setWidth(15);
      $sheet->getColumnDimension('H')->setWidth(15);
      $sheet->getColumnDimension('I')->setWidth(15);
      $sheet->getColumnDimension('J')->setWidth(15);
      $sheet->getColumnDimension('K')->setWidth(15);
      $sheet->getColumnDimension('L')->setWidth(20);
      $sheet->getColumnDimension('M')->setWidth(20);
      $sheet->getColumnDimension('N')->setWidth(20);

      $sheet->setCellValue('A1', '售出日期');
      $sheet->setCellValue('B1', '订单号');
      $sheet->setCellValue('C1', '分类');
      $sheet->setCellValue('D1', '商品名称');
      $sheet->setCellValue('E1', '采购日期');
      $sheet->setCellValue('F1', '单位');
      $sheet->setCellValue('G1', '数量');
      $sheet->setCellValue('H1', '成本');
      $sheet->setCellValue('I1', '总成本');
      $sheet->setCellValue('J1', '状态');
      $sheet->setCellValue('K1', '售价');
      $sheet->setCellValue('L1', '总售价');
      $sheet->setCellValue('M1', '流向');
      $sheet->setCellValue('N1', '备注');

      $row = 1;
      foreach($list as $v){
        $row++;
        $sheet->setCellValue("A{$row}", $v['insert_time']);
        $sheet->setCellValue("B{$row}", $v['sell_number']);
        $sheet->setCellValue("C{$row}", $v['category_name']);
        $sheet->setCellValue("D{$row}", $v['name']);
        $sheet->setCellValue("E{$row}", $v['sale_time']);
        $sheet->setCellValue("F{$row}", $v['unit']);
        $sheet->setCellValue("G{$row}", $v['count']);
        $sheet->setCellValue("H{$row}", $v['price']);
        $sheet->setCellValue("I{$row}", $v['total_cost']);
        $sheet->setCellValue("J{$row}", $v['type']);
        $sheet->setCellValue("K{$row}", $v['sell_price']);
        $sheet->setCellValue("L{$row}", $v['total_sell']);
        $sheet->setCellValue("M{$row}", $v['base_name']);
        $sheet->setCellValue("N{$row}", $v['comment']);
      }
    } else {
      $sheet->getColumnDimension('A')->setWidth(20);
      $sheet->getColumnDimension('B')->setWidth(15);
      $sheet->getColumnDimension('C')->setWidth(15);
      $sheet->getColumnDimension('D')->setWidth(20);
      $sheet->getColumnDimension('E')->setWidth(15);
      $sheet->getColumnDimension('F')->setWidth(15);
      $sheet->getColumnDimension('G')->setWidth(15);
      $sheet->getColumnDimension('H')->setWidth(15);
      $sheet->getColumnDimension('I')->setWidth(15);
      $sheet->getColumnDimension('J')->setWidth(15);

      $sheet->setCellValue('A1', '售出日期');
      $sheet->setCellValue('B1', '订单号');
      $sheet->setCellValue('C1', '分类');
      $sheet->setCellValue('D1', '商品名称');
      $sheet->setCellValue('E1', '采购日期');
      $sheet->setCellValue('F1', '单位');
      $sheet->setCellValue('G1', '数量');
      $sheet->setCellValue('H1', '状态');
      $sheet->setCellValue('I1', '流向');
      $sheet->setCellValue('J1', '备注');

      $row = 1;
      foreach($list as $v){
        $row++;
        $sheet->setCellValue("A{$row}", date('Y-m-d', strtotime($v['insert_time'])));
        $sheet->setCellValue("B{$row}", $v['sell_number']);
        $sheet->setCellValue("C{$row}", $v['category_name']);
        $sheet->setCellValue("D{$row}", $v['name']);
        $sheet->setCellValue("E{$row}", date('Y-m-d', strtotime($v['sale_time'])));
        $sheet->setCellValue("F{$row}", $v['unit']);
        $sheet->setCellValue("G{$row}", $v['count']);
        $sheet->setCellValue("H{$row}", $v['type'] === 1 ?  '加工' : '售出');
        $sheet->setCellValue("I{$row}", $v['base_name']);
        $sheet->setCellValue("J{$row}", $v['comment']);
      }
    }
    header("Content-type: application/octet-stream;charset=utf-8");
    header('Content-Disposition: attachment;filename="出库明细导出.xlsx"');
    header('Cache-Control: max-age=0');
    $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
    $writer->save('php://output');
  }
}